import axios from 'axios'
// import mainStore from '@/store/main'
import Cookies from 'js-cookie'
// import { useRouter } from 'vue-router'
import { getLangHeader } from '@/utils/lang'
import { useUserStore } from '@/stores/user'
import { setCookie } from '@/utils/cookie'
import i18next from '@/lang'
// const router = useRouter()

const VITE_API_BASE_URL = import.meta.env.VITE_API_BASE_URL

const my_lang =
  Cookies.get('language') ||
  localStorage.getItem('RCEP_LANG') ||
  navigator.language ||
  navigator.userLanguage

const service = axios.create({
  baseURL: VITE_API_BASE_URL,
  // timeout: 6000,
  withCredentials: false,
  headers: {
    'Content-Type': 'application/json;charset=utf-8',
    language: getLangHeader(my_lang),
  },
})

// 添加请求拦截器
service.interceptors.request.use(
  function (config) {
    // const store = mainStore()
    // if (config.loading) {
    //   store.loading = true
    // }

    // if (config.companyId === 1) {
    //   config.data.companyId = store.userInfo.companyId
    // }
    if (Cookies.get('token')) {
      // console.log();

      config.headers['Authorization'] = `Bearer  ${Cookies.get('token')}`
    }
    if (Cookies.get('language')) {
      // console.log();

      config.headers['Language'] = `${getLangHeader(Cookies.get('language'))}`
    }

    // 判断是上传文件接口
    if (config.url.includes('/smsemail/api/file/upload')) {
      config.headers['Content-Type'] = 'multipart/form-data'
    }

    return config
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error)
  },
)

// 添加响应拦截器
service.interceptors.response.use(
  function ({ data, config }) {
    // const store = mainStore()
    // if (config.loading) {
    //   store.loading = false
    // }
    if (data.code === 997) {
      // 单ip多次访问识别营业执照接口导致
      ElMessageBox.confirm('调用接口频繁，请稍后重试！', {
        confirmButtonText: '确定',
        showCancelButton: false,
        center: true,
      })
      return data
    } else if (data.code !== 20000 && data.code !== 998) {
      ElMessage({
        message: '数据出错',
        type: 'error',
        duration: 2000,
        showClose: true,
      })
      return Promise.reject(data)
    } else if (config.msg) {
      ElMessage({
        message: config.msg,
        type: 'success',
        duration: 2000,
        showClose: true,
      })
    }

    return data
  },
  function (error) {
    let flag = false
    const originMap = {
      'http://localhost:6600': 'http://localhost:8880',
      'https://sht.rcep.cn': 'https://www.rcep.cn',
      'https://tsht.rcepmart.com': 'https://tpc.rcepmart.com',
      'http://www.rcepdev.com:6600': 'http://www.rcepdev.com:8880',
    }

    if (error.response.status === 401) {
      useUserStore().removeUser()
      if (!flag) {
        flag = true
        ElMessage({
          message: '登录过期',
          type: 'error',
          duration: 2000,
          showClose: true,
          onClose: () => {
            flag = false
          },
        })
      }
      let str = ''
      if (window.location.host === 'localhost:8880') str = import.meta.env.VITE_DOMAIN_URL
      else if (window.location.host === 'www.rcepdev.com:8880') str = '.rcepdev.com'
      else {
        const host = window.location.host
        const arr = host.split('.')
        str = '.' + arr[arr.length - 2] + '.' + arr[arr.length - 1]
      }
      Cookies.remove('token', { domain: str })
      // Cookies.
      window.location.href = window.location.origin + '/login'
    } else if (error.response.status === 429) {
      ElMessage({
        message: '请求过于频繁',
        type: 'error',
        duration: 2000,
        showClose: true,
      })
    } else {
      ElMessage({
        message: '服务器开小差',
        type: 'error',
        duration: 2000,
        showClose: true,
      })
    }

    return Promise.reject(error)
  },
)

export default service
